// Package common
// @Author CN華少 2024/9/28 下午5:29
package common

import (
    "FinancialManagement/src/base/baselog"
    "FinancialManagement/src/base/db"
    "fmt"
    "strconv"

    "go.uber.org/zap"
)

// GetAnnualProcurementOfVehicles
// @Description: 获取特定年份下不同采购车辆的实际采购总金额、总数量、总运费
// @param yearId
func GetAnnualProcurementOfVehicles(yearId string) ([]AnnualProcurementOfVehicleSummary, error) {
    y, _ := strconv.Atoi(yearId)
    start := fmt.Sprintf("%s-01-01", yearId)
    end := fmt.Sprintf("%d-01-01", y+1)
    sql := fmt.Sprintf("SELECT pd.purchase_vehicle,SUM(pd.purchase_actual_amount) as sjzj,sum(pd.purchase_total) as zjs,sum(pd.purchase_freight) as zyf FROM purchase_detail as pd WHERE pd.purchase_departuredate >= '%s' AND pd.purchase_departuredate < '%s' AND pd.purchase_status !=3 GROUP BY pd.purchase_vehicle",
        start, end)
    rows, err := db.Res.DB.GetDbR().Debug().Raw(sql).Rows()
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    res := make([]AnnualProcurementOfVehicleSummary, 0)
    for rows.Next() {
        var item AnnualProcurementOfVehicleSummary
        if err := rows.Scan(
            &item.PurchaseVehicle,
            &item.Sjzj,
            &item.Zjs,
            &item.Zyf,
        ); err != nil {
            baselog.Logger.Error("解析年度采购车辆汇总失败", zap.Error(err))
            continue
        }
        res = append(res, item)
    }
    return res, nil
}

// GetActualSalesOfVehicles
// @Description: 获取特定年份下不同车辆的实际销售总金额、总利润
// @param yearId
// @return []map[string]interface{}
// @return error
func GetActualSalesOfVehicles(yearId string) ([]ActualSalesOfVehicleSummary, error) {
    y, _ := strconv.Atoi(yearId)
    start := fmt.Sprintf("%s-01-01", yearId)
    end := fmt.Sprintf("%d-01-01", y+1)
    sql := fmt.Sprintf("SELECT pd.purchase_vehicle,SUM(sd.sales_actual_total_price) as zjatp,SUM(sd.sales_pure_profit)as zjclr FROM sales_detail as sd LEFT JOIN purchase_detail as pd ON pd.purchase_id = sd.purchase_id  WHERE sd.sales_status !=3 AND pd.purchase_departuredate >= '%s' AND pd.purchase_departuredate < '%s' GROUP BY pd.purchase_vehicle", start, end)
    rows, err := db.Res.DB.GetDbR().Debug().Raw(sql).Rows()
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    res := make([]ActualSalesOfVehicleSummary, 0)
    for rows.Next() {
        var item ActualSalesOfVehicleSummary
        if err := rows.Scan(
            &item.PurchaseVehicle,
            &item.Zjatp,
            &item.Zjclr,
        ); err != nil {
            baselog.Logger.Error("解析年度销售车辆汇总失败", zap.Error(err))
            continue
        }
        res = append(res, item)
    }
    return res, nil
}

// GetPurchaseListOfYear
// @Description: 依据年份、客户ID获取不同客户总金额和斤数
// @param yearId
// @param ctId
// @return []map[string]interface{}
// @return error
func GetPurchaseListOfYear(yearId int, ctId int) ([]PurchaseYearMonthlySummary, error) {
    start := fmt.Sprintf("%d-01-01", yearId)
    end := fmt.Sprintf("%d-01-01", yearId+1)
    sqlWhere := fmt.Sprintf(" pdi.item_date >= '%s' AND pdi.item_date < '%s' ", start, end)
    if ctId != 0 {
        sqlWhere = fmt.Sprintf(" %s AND c.customer_id = %d ", sqlWhere, ctId)
    }
    sql := fmt.Sprintf("SELECT c.customer_id as customerId,c.name AS customer_name,DATE_FORMAT(pdi.item_date, '%%Y-%%m') AS month,YEAR(pdi.item_date) AS year,SUM(pdi.quantity) AS total_quantity,SUM(pdi.actual_amount) AS total_actual_amount FROM purchase_detail_item pdi JOIN purchase_detail pd ON pdi.purchase_id = pd.purchase_id JOIN customer c ON pdi.customer_id = c.customer_id WHERE %s GROUP BY c.name, YEAR(pdi.item_date), DATE_FORMAT(pdi.item_date, '%%Y-%%m') ORDER BY c.name, year, month",
        sqlWhere)
    rows, err := db.Res.DB.GetDbR().Debug().Raw(sql).Rows()
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    res := make([]PurchaseYearMonthlySummary, 0)
    for rows.Next() {
        var item PurchaseYearMonthlySummary
        if err := rows.Scan(
            &item.CustomerID,
            &item.CustomerName,
            &item.Month,
            &item.Year,
            &item.TotalQuantity,
            &item.TotalActualAmount,
        ); err != nil {
            baselog.Logger.Error("解析年度采购汇总失败", zap.Error(err))
            continue
        }
        res = append(res, item)
    }
    return res, nil
}

// GetSalesListOfYear
// @Description: 依据年份、销售ID获取不同销售总金额和斤数
// @param yearId
// @param salesId
// @return []map[string]interface{}
// @return error
func GetSalesListOfYear(yearId int, customerId int) ([]SalesYearMonthlySummary, error) {
	start := fmt.Sprintf("%d-01-01", yearId)
	end := fmt.Sprintf("%d-01-01", yearId+1)
	sqlWhere := fmt.Sprintf(" sdi.sdi_date >= '%s' AND sdi.sdi_date < '%s' ", start, end)
	if customerId != 0 {
		sqlWhere = fmt.Sprintf(" %s AND c.customer_id =%d ", sqlWhere, customerId)
	}
	sql := fmt.Sprintf("SELECT c.customer_id as customerId,c.name AS customer_name,DATE_FORMAT(sdi.sdi_date, '%%Y-%%m') AS month,YEAR(sdi.sdi_date) AS year,SUM(sdi.sdi_quantity) AS total_quantity,SUM(sdi.sdi_actual_amount) AS total_actual_amount FROM sales_detail_item sdi JOIN sales_detail sd ON sdi.sales_id = sd.sales_id JOIN customer c ON sdi.customer_id = c.customer_id WHERE %s GROUP BY c.name, YEAR(sdi.sdi_date), DATE_FORMAT(sdi.sdi_date, '%%Y-%%m') ORDER BY c.name, year, month", sqlWhere)
	rows, err := db.Res.DB.GetDbR().Debug().Raw(sql).Rows()
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	res := make([]SalesYearMonthlySummary, 0)
	for rows.Next() {
		var item SalesYearMonthlySummary
		if err := rows.Scan(
			&item.CustomerID,
			&item.CustomerName,
			&item.Month,
			&item.Year,
			&item.TotalQuantity,
			&item.TotalActualAmount,
		); err != nil {
			baselog.Logger.Error("解析年度销售汇总失败", zap.Error(err))
			continue
		}
		res = append(res, item)
	}
	return res, nil
}
